/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

enum{
	GAME_STATE_IDLE = 0,
	GAME_STATE_PLAYING,
};

#define LED4_ON()  HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7,GPIO_PIN_SET)
#define LED4_OFF()  HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7,GPIO_PIN_RESET)

#define LED5_ON()  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_1,GPIO_PIN_SET)
#define LED5_OFF()  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_1,GPIO_PIN_RESET)

#define LED6_ON()  HAL_GPIO_WritePin(GPIOI, GPIO_PIN_11,GPIO_PIN_SET)
#define LED6_OFF()  HAL_GPIO_WritePin(GPIOI, GPIO_PIN_11,GPIO_PIN_RESET)

#define LED7_ON()  HAL_GPIO_WritePin(GPIOI, GPIO_PIN_10,GPIO_PIN_SET)
#define LED7_OFF()  HAL_GPIO_WritePin(GPIOI, GPIO_PIN_10,GPIO_PIN_RESET)

#define IS_KEY3_PRESSED()  (HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_9) == GPIO_PIN_RESET)
#define IS_KEY4_PRESSED()  (HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_2) == GPIO_PIN_RESET)
#define IS_KEY5_PRESSED()  (HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_1) == GPIO_PIN_RESET)
#define IS_KEY6_PRESSED()  (HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_0) == GPIO_PIN_RESET)

void SystemClock_Config(void);
void switchState(int state);

static uint8_t gSegMap[10] = {0xfc,0x60,0xda,0xf2,0x66,0xb6,0xbe,0xE0,0xFE,0xF6};
static int gGameState;
uint8_t gKeyState;
uint8_t newGameEvent;
int gBeepTimeout = 0;
int gGameTimeLeft = 0;
int gGameScore = 0;

void BeepOn(int timeout){
	if (gBeepTimeout > 0){
		gBeepTimeout = timeout;
	} else{
		gBeepTimeout = timeout;
		HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1);
	}
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance == TIM3)
	{
		if (gGameState == GAME_STATE_IDLE){
			//
			HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_7);
			HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_1);
			HAL_GPIO_TogglePin(GPIOI, GPIO_PIN_11);
			HAL_GPIO_TogglePin(GPIOI, GPIO_PIN_10);
		} else{
			if (gGameTimeLeft > 0){
				uint8_t buf[8];

				gGameTimeLeft--; //时间时间少
				buf[0] = gSegMap[gGameTimeLeft/10];
				buf[1] = gSegMap[gGameTimeLeft%10];
				HAL_I2C_Mem_Write(&hi2c1,0x70, 0x10, 1, buf, 2, 100);

				if (gGameTimeLeft == 0){
					//游戏结束
					BeepOn(1000);
					//重新进入空闲状态
					switchState(GAME_STATE_IDLE);
				}
			}


		}

		//printf("gGameTimeLeft=%d..state=%d\r\n", gGameTimeLeft, gGameState);

	} else if(htim->Instance == TIM5){

		if (gBeepTimeout > 0){
			gBeepTimeout -= 100;
			if (gBeepTimeout <= 0){
				//beep时间超时了
				HAL_TIM_PWM_Stop(&htim4, TIM_CHANNEL_1);
			}
		}
	}
}

uint8_t ScanKeyLoop(){

	uint8_t keyEvent = 0; //按键事件

	if ((gKeyState & 0x01) == 0){
		if (IS_KEY3_PRESSED()){
			//消抖
			HAL_Delay(10);
			if (IS_KEY3_PRESSED()){
				gKeyState |= 0x01;
				keyEvent |= 0x01;
			}
		}
	} else{
		//按下状态
		if (!IS_KEY3_PRESSED()){
			//松开事件
			gKeyState &= ~0x01;
			keyEvent |= 0x10;
		}
	}

	if ((gKeyState & 0x02) == 0){
		if (IS_KEY4_PRESSED()){
			//消抖
			HAL_Delay(10);
			if (IS_KEY4_PRESSED()){
				gKeyState |= 0x02;
				keyEvent |= 0x02;
			}
		}
	} else{
		//按下状态
		if (!IS_KEY4_PRESSED()){
			gKeyState &= ~0x02;
			keyEvent |= 0x20;
		}
	}

	if ((gKeyState & 0x04) == 0){
		if (IS_KEY5_PRESSED()){
			//消抖
			HAL_Delay(10);
			if (IS_KEY5_PRESSED()){
				gKeyState |= 0x04;
				keyEvent |= 0x04;
			}
		}
	} else{
		//按下状态
		if (!IS_KEY5_PRESSED()){
			gKeyState &= ~0x04;
			keyEvent |= 0x40;
		}
	}

	if ((gKeyState & 0x08) == 0){
		if (IS_KEY6_PRESSED()){
			//消抖
			HAL_Delay(10);
			if (IS_KEY6_PRESSED()){
				gKeyState |= 0x08;
				keyEvent |= 0x08;
			}
		}
	} else{
		//按下状态
		if (!IS_KEY6_PRESSED()){
			gKeyState &= ~0x08;
			keyEvent |= 0x80;
		}
	}

	return keyEvent;
}

void switchState(int state){
	uint8_t buf[8];
	int i;

	if (state == gGameState){
		return;
	}

	gGameState = state;

	if (gGameState == GAME_STATE_IDLE){
		LED4_OFF();
		LED5_OFF();
		LED6_OFF();
		LED7_OFF();

		HAL_TIM_Base_Stop_IT(&htim3);

		//写一条横线

	} else{
		//进入游戏状态

		//重新设定定时器

		htim3.Init.Period = 1000;
		HAL_TIM_Base_Init(&htim3);

		//启动定时器
		HAL_TIM_Base_Start_IT(&htim3);

		LED4_OFF();
		LED5_OFF();
		LED6_OFF();
		LED7_OFF();

		//重新生成随机数种子
		srand((int)HAL_GetTick());

		//后面的不显示
		for(i=0; i<8; i++){
			buf[i] = 0x02;
		}

		//在空闲状态写写入这个吧
		HAL_I2C_Mem_Write(&hi2c1,0x70, 0x10, 1, buf,8, 100);

		//定义新的游戏状态
		newGameEvent = 0;
		//60s
		gGameTimeLeft = 60;

		//游戏得分
		gGameScore = 0;

		BeepOn(1000);
	}
}

int main(void)
{
	uint8_t keyEvent = 0;
	uint8_t buf[8];

	HAL_Init();

	if(IS_ENGINEERING_BOOT_MODE())
	{
		/* Configure the system clock */
		SystemClock_Config();
	}

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_I2C1_Init();
	MX_TIM4_Init();
	MX_UART4_Init();
	MX_TIM3_Init();
	MX_TIM5_Init();

	HAL_TIM_Base_Start_IT(&htim5);

	//游戏开始
	printf("game start...\r\n");

	switchState(GAME_STATE_IDLE);
	gKeyState = 0;

	BeepOn(1000);

	newGameEvent = 0;
	while (1)
	{
		HAL_Delay(1);

		keyEvent = ScanKeyLoop();
		if (keyEvent != 0){
			printf("keyEvent=0x%02x\r\n", keyEvent);
		}

		//游戏主循环
		if (gGameState == GAME_STATE_IDLE){
			if (keyEvent == 0x01){ //key3按下，开始进入
				int i;

				printf("start playing\r\n");
				for(i=0; i<8; i++){
					buf[i] = 0x02;
				}
				//在空闲状态写写入这个吧
				HAL_I2C_Mem_Write(&hi2c1,0x70, 0x10, 1, buf,8, 100);

				switchState(GAME_STATE_PLAYING);
			}
		} else if (gGameState == GAME_STATE_PLAYING){

			if (gGameTimeLeft > 0){
				if (newGameEvent == 0){
					//生成一个新的按键事件
					int idx1, idx2;
					idx1 = rand()%4;
					idx2 = rand()%4;
					//生成一个随机的按键
					newGameEvent = (0x01<<idx1)|(0x01<<idx2);

					if (newGameEvent & 0x01){
						LED4_ON();
					} else{
						LED4_OFF();
					}

					if (newGameEvent & 0x02){
						LED5_ON();
					} else{
						LED5_OFF();
					}

					if (newGameEvent & 0x04){
						LED6_ON();
					} else{
						LED6_OFF();
					}

					if (newGameEvent & 0x08){
						LED7_ON();
					} else{
						LED7_OFF();
					}
				} else{
					if (gKeyState == newGameEvent){
						//按键匹配
						gGameScore++;

						//更新得分
						buf[0] = gSegMap[gGameScore/10];
						buf[1] = gSegMap[gGameScore%10];
						HAL_I2C_Mem_Write(&hi2c1,0x70, 0x12, 1, buf, 2, 100);

						//按键响应
						BeepOn(200);

						newGameEvent = 0;
					}
				}
			}

		}
	}
}

void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.HSIDivValue = RCC_HSI_DIV1;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  RCC_OscInitStruct.PLL2.PLLState = RCC_PLL_NONE;
  RCC_OscInitStruct.PLL3.PLLState = RCC_PLL_NONE;
  RCC_OscInitStruct.PLL4.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** RCC Clock Config
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_ACLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_PCLK3|RCC_CLOCKTYPE_PCLK4
                              |RCC_CLOCKTYPE_PCLK5;
  RCC_ClkInitStruct.AXISSInit.AXI_Clock = RCC_AXISSOURCE_HSI;
  RCC_ClkInitStruct.AXISSInit.AXI_Div = RCC_AXI_DIV1;
  RCC_ClkInitStruct.MCUInit.MCU_Clock = RCC_MCUSSOURCE_HSI;
  RCC_ClkInitStruct.MCUInit.MCU_Div = RCC_MCU_DIV1;
  RCC_ClkInitStruct.APB4_Div = RCC_APB4_DIV1;
  RCC_ClkInitStruct.APB5_Div = RCC_APB5_DIV1;
  RCC_ClkInitStruct.APB1_Div = RCC_APB1_DIV1;
  RCC_ClkInitStruct.APB2_Div = RCC_APB2_DIV1;
  RCC_ClkInitStruct.APB3_Div = RCC_APB3_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */


#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
PUTCHAR_PROTOTYPE
{
 HAL_UART_Transmit(&huart4,(uint8_t*)&ch,1,HAL_MAX_DELAY);
 return ch;
}
#endif
